import React from "react";
import {Select,Button, Modal, Form,Checkbox, Col, Row, Input} from 'antd/lib';
import notification from "@/services/notification";
import {get} from "lodash";
import Uploads from "@/services/uploads";
import 'antd/dist/antd.less'
import moment from "moment";
import Customer from "@/services/customer";
import DatePicker from "antd/lib/date-picker";
import locale from 'antd/es/date-picker/locale/zh_CN';
import { currentUser} from "@/services/auth";
import ContractSuspend from "@/services/contractsuspend";
import Contracts from "@/services/contracts";
import ContractApply from "@/services/contractapply";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
import Attaches from "@/services/attaches";
import {StarOutlined, UploadOutlined} from '@ant-design/icons';
import Upload from "antd/lib/upload";
import GlobalFunctions from '@/store/globalFunctions';
import { inject, observer } from 'mobx-react';
const { confirm } = Modal;

class SuspendTable extends React.Component {
  state = {
    loading: true,

    contractsdata:[],
    departmentdata:[],
    handledeptdata:[],
    annex:[],//--附件
  };
  // componentDidMount() {
  //   const userId = this.props.userId || currentUser.id;
  // }
  componentWillMount() {
    let id=this.props.id+'';
    if(id.substr(0,3) !== "daz") {
      Attaches.get({sourceid:id,type:"contractsuspend" }).then(data => {
        this.setState({
          annex: data.annex,
        });
      }).catch(error => {
      });
    }
    id=  this.props.id.replace('daz','');

    let param={
      billtype: "contractsuspend",
      id: id,
    }
    Contracts.getsellist(param).then(data => {
      this.setState({
        contractsdata: data,
        loading:false,
      });
    });
      //HRP部门表
    param={
        code: "",
        name: "",
        userid: currentUser.id,
      }
      Customer.querydepartment(param).then(data => {
        this.setState({
          departmentdata: data,
        });
      });

    param={code: "",
    name: "",
    orgunit_id:0,
    userid: "0",
  }
    this.refreshData(param);
  }
  refreshData(param) {
     Customer.queryemployee(param).then(data => {
        this.setState({
          handledeptdata: data,
        });
    });
  }

 bill_dateonchange = (value) => {
  if (GlobalFunctions.isEmptyobj(value)) {
    return;
  }
  this.props.contractSuspendStore.contractSuspendModel.setBill_date(value);
 };

   handledown(file){
     let  filename=file.url;
     let names=file.name;
     if(names.split('.')[1]!==filename.split('.')[1]){
      filename=filename.split('.')[0] +'.'+names.split('.')[1];
     }
     let AjaxUrl = 'api/upload/downloadfile';
     fetch(AjaxUrl ,{
      method: 'POST',
      body: window.JSON.stringify({filename: filename}),
      credentials: 'include',
      headers: new Headers({
        'Content-Type': 'application/json'
      })}).then((response) => {
      response.blob().then(blob => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display='none';
        const objectUrl = window.URL.createObjectURL(blob);
        aLink.href = objectUrl;
        aLink.download = file.name;
        aLink.click();
        document.body.removeChild(aLink);
      });
    }).catch((error) => {
      console.log(error);
    });
  };
   getPdfURL(){
        const _this = this;
        const props = {
            name: 'file',
            action: 'api/upload/uploadfile/contractsuspend/editor/0/0/'+_this.props.contractSuspendStore.contractSuspendModel.id,
            headers: {
                authorization: 'authorization-text',
            },
         //  onChange: this.handleChange,
         onChange(info) {
                let fileList = [...info.fileList];

                // 1. Limit the number of uploaded files
                // Only to show two recent uploaded files, and old ones will be replaced by the new
                // fileList = fileList.slice(-2);
                // 2. Read from response and show file link
            var newd=[];
            fileList.forEach(file => {
                  if (file.response) {
                    // Component will show file.url as link
                    file.url = 'static/file/'+file.response.filename;
                  }
                  let status = _this.props.contractSuspendStore.contractSuspendModel.status;
                  if(file.bytstatus>=0){
                    status=file.bytstatus;
                  }
             // if(file.status==="done") {
                 const b=[{
                          uid: file.uid,
                          name: file.name,
                          status: file.status,
                          bytstatus: status,
                          url: file.url
                  }];
                if (newd.length < 1) {
                  newd = b;
                } else {
                  newd.push.apply(newd, b);
                }
             // }
                });
                _this.setState({ annex:newd });
              },
           onDownload: this.handledown,
           onRemove(infos){
            let uid=infos.uid;
            const id=_this.props.contractSuspendStore.contractSuspendModel.id;
            Uploads.removefile({sourcetype: "contractsuspend",sourceid:id,uid:uid}).then(data => {
                 if(data.code==="sucess"){
                    notification.success(data.msg);
                 }
                 else{
                  notification.error(data.msg);
                  }
                }).catch(error => {
                  notification.error(get(error, "response.data.message", "删除失败."));
                });
           },
            showUploadList: {
            showDownloadIcon: true,
            downloadIcon: '下载',
            showRemoveIcon: true,
            removeIcon: <StarOutlined onClick={e => console.log(e, 'custom removeIcon event')} />,
          },
        };
        return props;
    };
  departmentidchange= (value) => {    
    this.props.contractSuspendStore.contractSuspendModel.setDepartmentid(value);
 };
  contractchange= (value) => {
    let item = this.state.contractsdata.filter((p) => {
      return p.id === value;
    });
    if(item.length<1){
      return;
    }
    this.props.contractSuspendStore.contractSuspendModel.setContractsid(item[0]);
   };
  fieldedit(field){
    if(!this.props.contractSuspendStore.contractSuspendModel.isedit){
      return true;
    }
    if(this.props.contractSuspendStore.contractSuspendModel.colcontrol){
      if(this.props.contractSuspendStore.contractSuspendModel.allow_col.indexOf(field)>=0){
        return false;
      }else{
        return true;
      }
    }else{
      return false;
    }
  }
  render() {
    if (this.state.loading) return null;
    return(
      <div>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
      <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同编码">
              <Select 
                showSearch
                optionFilterProp="children"
              style={{ width:  400 }} 
              value={this.props.contractSuspendStore.contractSuspendModel.contractsid} 
              onChange={this.contractchange}  
              disabled ={this.fieldedit("contractsid")} >
              {(this.state.contractsdata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.code}</Select.Option>
              ))}
              </Select>
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="名称">
            <Input
                value={this.props.contractSuspendStore.contractSuspendModel.name}
                style={{ width:  400 }}
                onChange={e => this.props.contractSuspendStore.contractSuspendModel.setName(e.target.value)}
                disabled ={true}
                placeholder="名称"
              />
						</Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="经办部门">
              <Select style={{ width:  400 }}
                      showSearch
                      optionFilterProp="children"
                      value={this.props.contractSuspendStore.contractSuspendModel.departmentid}
                      onChange={this.departmentidchange} 
                      disabled ={this.fieldedit("departmentid")}>
              {(this.state.departmentdata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select>
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="经办人">
              <Select style={{ width:  400 }}
                      showSearch
                      optionFilterProp="children"
                      value={this.props.contractSuspendStore.contractSuspendModel.employeeid}
                      onChange={value => this.props.contractSuspendStore.contractSuspendModel.setEmployeeid(value)} 
                      disabled ={this.fieldedit("employeeid")}>
              {(this.state.handledeptdata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row >
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="记录事项">
              <textarea
                rows="5" cols="60"
                textAlignVertical="top"
                height="100px"
                value={this.props.contractSuspendStore.contractSuspendModel.message}
                onChange={e => this.props.contractSuspendStore.contractSuspendModel.setMessage(e.target.value)}
                placeholder="记录事项"
                disabled ={this.fieldedit("message")}
              />
						</Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="附件">
              <Upload {...this.getPdfURL()} fileList={this.state.annex} 
              disabled ={this.fieldedit("annex")}>
                <Button>
                  <UploadOutlined /> 上传
                </Button>
              </Upload>
						</Form.Item>
				  </Col>
        </Row>
      </Form>
      </div>
    );
  };
}

export default inject('contractSuspendStore')(observer(SuspendTable));